package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.ShoppingCar;
import cn.wolfcode.trip.base.mapper.ShoppingCarMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IShoppingCarService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCarServiceImpl implements IShoppingCarService {

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;


    @Override
    public int deleteByPrimaryKey(Long id) {
        int i = shoppingCarMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public int save(ShoppingCar shoppingCar) {
        //判断新加入购物车的商品在购物车中是否已存在?
        ShoppingCar car = new ShoppingCar();
        car.setProduct(shoppingCar.getProduct());
        car.setUser(shoppingCar.getUser());
        ShoppingCar car2 = shoppingCarMapper.selectOne(car);
        int i = 0;
        if (car2 != null) {    //该用户购物车中已存在该商品,直接数量加
            car2.setNum(car2.getNum() + shoppingCar.getNum());
            shoppingCarMapper.update(car2);
        }else {
            i = shoppingCarMapper.insert(shoppingCar);  //否则新增购物车
        }
        return i;
    }

    @Override
    public ShoppingCar selectByPrimaryKey(Long id) {
        return null;
    }

    @Override
    public List<ShoppingCar> selectAll() {
        return null;
    }


    @Override
    public List<ShoppingCar> getShoppingCarList(Long[] ids) {
        List<ShoppingCar> list = new ArrayList<>();
        if (ids!=null){
            for (Long id : ids) {
                ShoppingCar shoppingCar = shoppingCarMapper.selectByPrimaryKey(id);
                list.add(shoppingCar);
            }
        }
        return list;
    }

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<ShoppingCar> list =  shoppingCarMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public int updateByPrimaryKey(ShoppingCar shoppingCar) {
        int i = shoppingCarMapper.update(shoppingCar);
        return i;
    }


}
